package com.yayako.utils.EasyExcel;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.yayako.modules.department.entity.Department;
import com.yayako.modules.department.service.DeptService;
import com.yayako.utils.common.ApplicationContextUtil;

/** @author cyy */
public class CustomConverter implements Converter<Object> {
  private DeptService deptService = ApplicationContextUtil.getBean(DeptService.class);

  /**
   * 实体类支持数据类型
   *
   * @return 实体类支持数据类型
   */
  @Override
  public Class supportJavaTypeKey() {
    return Object.class;
  }

  /**
   * excel支持数据类型
   *
   * @return excel支持数据类型
   */
  @Override
  public CellDataTypeEnum supportExcelTypeKey() {
    return CellDataTypeEnum.STRING;
  }

  /**
   * 导入时调用的数据转换
   *
   * @param cellData 单元格数据
   * @param excelContentProperty
   * @param globalConfiguration
   * @return 数据库数据
   * @throws Exception
   */
  @Override
  public Object convertToJavaData(
      CellData cellData,
      ExcelContentProperty excelContentProperty,
      GlobalConfiguration globalConfiguration)
      throws Exception {
    Object o = null;
    if (excelContentProperty.getField().getType() == Department.class) {
      o = deptService.getDeptByName(cellData.getStringValue());
    }

    return o;
  }

  /**
   * 导出时调用的数据转换
   *
   * @param o 数据库数据
   * @param excelContentProperty
   * @param globalConfiguration
   * @return 单元格数据
   * @throws Exception
   */
  @Override
  public CellData convertToExcelData(
      Object o, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration)
      throws Exception {
    CellData cellData = new CellData("");
    if (excelContentProperty.getField().getType() == Department.class) {
      cellData = new CellData(((Department) o).getName());
    }
    return cellData;
  }
}
